<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Auth;

class UsersController extends Controller
{
    const PAGE_SIZE = 10;

    public function __construct()
    {
        $this->middleware('auth',[
            'except'  => ['show', 'create', 'store', 'index', 'confirmEmail']
        ]);

        $this->middleware('guest',[
            'only'  => ['create'],
        ]);
    }

    public function index()
    {
        $users = User::paginate(self::PAGE_SIZE);
        return view('users.index', compact('users'));
    }

    public function create()
    {
        return view('users.create');
    }

    public function show(User $user)
    {
        $statuses = $user->statuses()->orderBy('created_at', 'desc')->paginate(10);
        return view('users.show', compact('user', 'statuses'));
    }

    /**
     * 保存用户注册信息
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $result = $this->validate($request, [
            'name' => 'required|max:50',
            'email' => 'required|email|unique:users|max:60',
            'password' => 'required|confirmed|min:6'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

        self::sendEmailConfirmationTo($user);
        session()->flash('success', '验证邮箱已经发送到您的注册邮箱上，请注册查收。');
        return redirect('/');
    }

    /**
     * 显示更新页面
     *
     * @param User $user
     * @return mixed
     */
    public function edit(User $user)
    {
        $this->authorize('update', $user);
        return view('users.edit', compact('user'));
    }

    /**
     * 更新用户信息
     *
     * @param User $user
     * @param Request $request
     * @return mixed
     */
    public function update(User $user, Request $request)
    {
        $this->validate($request,[
            'name'  => 'required|max:50',
            'password'=>'nullable|confirmed|min:6'
        ]);
        $this->authorize('update', $user);

        $data = [];
        $data['name'] = $request->name;
        if ($request->password){
            $data['password'] = bcrypt($request->password);
        }
        $user->update($data);
        session()->flash('success', '个人资料更新成功！');

        return redirect()->route('users.show', $user->id);
    }

    public function destroy(User $user)
    {
        $this->authorize('destroy', $user);
        $user->delete();
        session()->flash('success', '成功删除用户！');
        return back();
    }

    public function confirmEmail($token)
    {
        $user = User::where('activation_token', $token)->firstOrFail();

        $user->activated = true;
        $user->activation_token = null;
        $user->save();

        Auth::login($user);
        session()->flash('success', '恭喜您，激活成功');
        return redirect()->route('users.show', [$user]);
    }

    /**
     * 发送激活邮件
     *
     * @param $user
     */
    private function sendEmailConfirmationTo($user)
    {
        $view = 'emails.confirm';
        $data = compact('user');
        $from = 'huangcong09@126.com';
        $name = 'huangcont';
        $to = $user->email;
        $subject = "感谢注册Sample应用！请确认您的邮箱";

        Mail::send($view, $data, function ($message) use ($from, $name, $to, $subject) {
            $message->from($from, $name)->to($to)->subject($subject);
        });
    }
}
